<template>
  <div class="search">
 <search
    v-model="keywords"
    show-action
    :autofocus="autovalue"
    autocomplete
    shape="round"
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @update:model-value="oninput"
  >
  <template #left>
    <icon name="arrow-left" color="#333" @click="onClick"/>
  </template>
  <template #action>
    <div @click="onClickButton">搜索</div>
  </template>
  </search>
  <ul>
      <li v-for="item in content" v-html="`${highLight(item.name)}`" :key="item.id" class="searchLi">
  
      </li>
    </ul>
</div>
</template>
<script setup>
import { Search ,Toast,Icon} from 'vant';
import { useRoute ,useRouter} from "vue-router";
import { loadProductsAPI } from "../services/product";
import { ref} from "vue";
    const router = useRouter();
    const keywords = ref('');
    const autovalue=ref(true);
    const content=ref([]);
    const highLight=(txt)=> {
          //对关键词做高亮处理
        
          return keywords.value
            ? txt.replace(keywords.value, `<span class="hightTxt">${keywords.value}</span>`)
            : txt;
        }
    const onSearch = (val) => Toast(val);
    const onClickButton = () => {
      content.value = [];
      if(keywords.value!=''){
      loadProductsAPI().then((res)=>{
        content.value = res.data.filter(
            (item) => item.name.indexOf(keywords.value) > -1
          );
  })}
    }
    const onClick=()=>{
      router.push({
        name: "Like",
      });
    }
    //搜索框内容发生变化时触发
    const oninput=(val)=>{
      content.value = [];
      if(val!=''){
      loadProductsAPI().then((res)=>{
        content.value = res.data.filter(
            (item) => item.name.indexOf(keywords.value) > -1
          );
  })}
    }
</script>
<style>
.hightTxt{
      color: red;
    }
.searchLi{
  padding: 1rem;
  text-align: left;
}
</style>
